package com.heima.article.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.filer.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.runtime.Log;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult load(ArticleHomeDto dot) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dot, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dot) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dot, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dot) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dot, 2);
        return ResponseResult.okResult(apArticles);
    }


    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Override
    public void generate(Long articleId) {
        //查询ApArticleContent表，获得里面的content数据
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if (apArticleContent == null) {
            log.warn("文章内容不存在");
            return;
        }

        //创建一个数据集合Map,把上一步的content数据赋值到map的content字段上
        Map<String, Object> map = new HashMap<>(1);
        map.put("content", JSON.parseArray(apArticleContent.getContent()));
        //调用Freemarker插件，生成html的页面
        InputStream generate = freemarkerGenerator.generate("article.ftl", map);
        //调用MinIo插件，上传html的页面
        String s = minIoTemplate.uploadFile("", articleId + ".html", generate, "html");
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.warn("文章为空");
            return;
        }
        apArticle.setStaticUrl(s);
        //更新ApArticle，修改里面static_url字段
        apArticleMapper.updateById(apArticle);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        //前端传入的参数是否为空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        Long id = dto.getId();
        String content = dto.getContent();
        //组装article表数据
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);

        //判断dto里面的id是否存在
        if (id == null) {
            //不存在就新增
            //插入article表
            int insert = apArticleMapper.insert(apArticle);
            if (insert<1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"插入失败");
            }
            //插入article_config表
            //组装config表数据
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsComment(true);
            apArticleConfig.setArticleId(apArticle.getId());
            int insert1 = apArticleConfigMapper.insert(apArticleConfig);
            if (insert1<1){
                log.warn("文章的配置表插入失败 ");
                throw new RuntimeException("文章配置表插入失败");
            }
          //调用现成方法，实现文章详情的生成和更新
            generate(apArticle.getId());


            //插入article_content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);
            apArticleContent.setArticleId(apArticle.getId());
            int insert2 = apArticleContentMapper.insert(apArticleContent);
            if (insert2<1){
                log.warn("文章的内容表插入失败 ");
                throw new RuntimeException("文章内容表插入失败");
            }

            return ResponseResult.okResult(apArticle.getId());
        } else {
            //id存在 修改
            //修改article
            int i = apArticleMapper.updateById(apArticle);
            if (i<1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章修改失败");
            }
            //修改article_content
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId,id);
            int update = apArticleContentMapper.update(apArticleContent, wrapper);
            if (update<1){
                log.warn("文章的内容表修改失败 ");
                throw new RuntimeException("文章内容表修改失败");
            }

            //调用详情生成
            generate(id);
            //articleId返回去
            return ResponseResult.okResult(id);
        }

    }
}
